<template>
  <div class="">
    <dl class="m-categroy">
      <dt>按拼音首字母选择：</dt>
      <dd
        v-for="item in list"
        :key="item"
      >
        <a :href="'#city-'+item">{{ item }}</a>
      </dd>
    </dl>
    <dl
      v-for="item in block"
      :key="item.title"
      class="m-categroy-section"
    >
      <dt :id="'city-'+item.title">
        {{ item.title }}
      </dt>
      <dd>
        <span
          v-for="c in item.city"
          :key="c"
          @click="handleSelect(c)"
        >{{ c }}</span>
      </dd>
    </dl>
  </div>
</template>

<script>
import pyjs from 'js-pinyin'
export default {
  data () {
    return {
      list: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''),
      block: []
    }
  },
  async created () {
    const { status, data: { city } } = await this.$axios.get('/geo/city')
    if (status === 200) {
      let p
      let c
      const d = {}
      city.forEach((item) => {
        p = pyjs.getFullChars(item.name).toLowerCase().slice(0, 1) // 把取到的值转为拼音，并均转为小写,并只取首字母
        c = p.charCodeAt(0) // 获取首字母的编码（code值）
        // 大写的A-Z,code值为65-90
        // 小写的a-z,code值为97-122
        if (c > 96 && c < 123) {
          if (!d[p]) { // d为临时对象
            d[p] = []
          }
          d[p].push(item.name)
        }
      })
      const blocks = []
      // 把临时对象内需要的内容整理为我们需要的格式
      for (const [k, v] of Object.entries(d)) {
        blocks.push({
          title: k.toUpperCase(),
          city: v
        })
      }
      // 排序
      blocks.sort((a, b) => {
        return a.title.charCodeAt(0) - b.title.charCodeAt(0)
      })
      this.block = blocks
    }
  },
  methods: {
    handleSelect (city) {
      this.$store.dispatch('geo/setPosition', {
        city
      })
      this.$router.push('/')
    }
  }
}
</script>

<style lang="scss">
  @import "@/assets/css/changeCity/categroy.scss";
</style>
